package com.strelitzia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.strelitzia.dao.ChatDao;
import com.strelitzia.entity.ChatEntity;
import com.strelitzia.entity.FriendsEntity;
import com.strelitzia.entity.UserEntity;
import com.strelitzia.filter.CorsFilter;
import com.strelitzia.service.ChatService;
import com.strelitzia.service.FriendsService;
import com.strelitzia.service.UserService;
import com.strelitzia.utils.TimeUtil;
import com.strelitzia.vo.ChatItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @create 2023/12/20 10:19
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatDao, ChatEntity> implements ChatService {
    @Autowired
    private UserService userService;

    @Autowired
    private FriendsService friendsService;

    @Override
    public List<ChatItem> getList() {
        List<ChatEntity> list = this.baseMapper.getList(CorsFilter.loginUserId.get());
        List<ChatItem> chatItems = new ArrayList<>();
        if (list != null) {
            chatItems = list.stream().map(item -> {
                ChatItem chatItem = new ChatItem();
                String[] str = item.getChatHistory().split("-");
                Integer fid;
                if (str.length != 0) {
                    fid = Integer.parseInt(str[1]);
                    if (fid.equals(CorsFilter.loginUserId.get())) {
                        fid = Integer.parseInt(str[0]);
                    }
                    chatItem.setFid(fid);
                    chatItem.setLastId(item.getLastSender());
                    chatItem.setNoRead(item.getNoRead());
                    chatItem.setContent(item.getLastChat());
                    UserEntity byId = userService.getById(fid);
                    chatItem.setAvatar("/api/res/" + byId.getAvatar());
                    FriendsEntity one = friendsService.getOne(new QueryWrapper<FriendsEntity>()
                            .eq("uid", CorsFilter.loginUserId.get())
                            .eq("friend_id", fid));
                    if (one != null && !one.getRemark().equals("")) {
                        chatItem.setRemark(one.getRemark());
                    } else {
                        chatItem.setRemark(byId.getNickname());
                    }
                    chatItem.setTime(TimeUtil.formattingTime(item.getUpdateTime()));
                    return chatItem;
                } else {
                    throw new RuntimeException();
                }
            }).collect(Collectors.toList());
        }
        return chatItems;
    }

    @Override
    public void addChat(Integer fid, String content) {
        ChatEntity chatEntity = new ChatEntity();
        Integer uid = CorsFilter.loginUserId.get();
        if (uid > fid) {
            chatEntity.setChatHistory(fid + "-" + uid);
        } else {
            chatEntity.setChatHistory(uid + "-" + fid);
        }
        chatEntity.setLastSender(uid);
        chatEntity.setLastChat(content);
        chatEntity.setUpdateTime(new Timestamp(new Date().getTime()));
        ChatEntity chat = this.getOne(new QueryWrapper<ChatEntity>().eq("chat_history", chatEntity.getChatHistory()));
        if (chat != null) {
            if (chat.getDelTag() != null && chat.getDelTag().equals(uid)) {
                chatEntity.setDelTag(0);
            }
            chatEntity.setId(chat.getId());
            chatEntity.setNoRead(chat.getNoRead() + 1);
            this.updateById(chatEntity);
        } else {
            chatEntity.setNoRead(1);
            this.save(chatEntity);
        }

    }

    @Override
    public void delChat(Integer fid) {
        Integer uid = CorsFilter.loginUserId.get();
        String chatHistory;
        if (uid > fid) {
            chatHistory = fid + "-" + uid;
        } else {
            chatHistory = uid + "-" + fid;
        }
        ChatEntity chatEntity = this.getOne(new QueryWrapper<ChatEntity>().eq("chat_history", chatHistory));
        if (chatEntity.getDelTag() == null || chatEntity.getDelTag() == 0) {
            chatEntity.setDelTag(uid);
            this.updateById(chatEntity);
        } else if (chatEntity.getDelTag().equals(fid)) {
            this.removeById(chatEntity.getId());
        }
    }
}
